using AndyPike.Commons.Persistence.NHibernate;
using AndyPike.Commons.Web;
using NHibernate;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using Rhino.Mocks;

namespace AndyPike.Commons.Tests.Unit.Persistence.NHibernate
{
    [TestFixture]
    public class When_locating_the_NHibernate_session
    {
        private MockRepository mockery;
        private INHibernateSessionLocater locater;
        private IHttpContext httpContext;

        [SetUp]
        public void SetUp()
        {
            mockery = new MockRepository();
            httpContext = mockery.DynamicMock<IHttpContext>();

            locater = new NHibernateHttpContextSessionLocater(httpContext);
        }

        [Test]
        public void Should_retrieve_the_session_from_the_http_context()
        {
            ISession session = null;
            var expectedSession = mockery.Stub<ISession>();

            With.Mocks(mockery)
                .Expecting(() => Expect.Call(httpContext.GetItem(null)).IgnoreArguments().Return(expectedSession))
                .Verify(() => session = locater.CurrentSession);
                        
            Assert.That(session, Is.EqualTo(expectedSession));
        }

        [Test]
        [ExpectedException(typeof(SessionException))]
        public void Should_throw_an_exception_if_the_session_cannot_be_found_in_the_http_context()
        {
            ISession session = null;

            With.Mocks(mockery)
                .Expecting(() => Expect.Call(httpContext.GetItem(null)).IgnoreArguments().Return(null))
                .Verify(() => session = locater.CurrentSession);
        }
    }
}